require 'rake/clean'

require 'time' # needed to add this to overcome strange activerdf issue: https://bugs.launchpad.net/activerdf/+bug/202979
require 'rubygems'
require 'active_rdf'
require 'activerdf_rules'

require 'lib/ldontospec'

CLEAN.include("*.sqlite3")

desc 'Cache the knowledge base'
task :build do
  prefix, ontology, path = ENV['prefix'], ENV['ontology'], ENV['path']
  if (prefix.nil? and ontology.nil?)
    puts 'Need to specify the prefix, URI and optionally the path to the ontology using: prefix=<prefix> ontology=<URI> path=<path to local file>'
    exit
  end
  ontospec = LDOntoSpec.new(prefix, ontology, path)
  adapter = ConnectionPool.add_data_source :type => :fetching, :location => "#{ontospec.prefix}.sqlite3"
  
  Namespace.register ontospec.prefix, ontospec.ontology_uri
  ObjectManager.construct_classes
  
  # load ontology RDF
  if (ontospec.local?)
    adapter.load ontospec.ontology_path
  else
    adapter.fetch ontospec.ontology_path    
  end
    
  MyRuleBase = RuleBase.new('MyRuleBase') {
    rule "unionOf" do
      condition :s, :p, :o
      condition :o, OWL::unionOf, :list
      condition :list, RDF::first, :thing

      conclusion :s, :p, :thing
    end
    rule "unionOf-rest" do
      condition :s, :p, :o
      condition :o, OWL::unionOf, :list
      # what if there is a longer list???
      condition :list, RDF::rest, :rest 
      condition :rest, RDF::first, :thing

      conclusion :s, :p, :thing
    end
  }
  
  re = RuleEngine.new
  re.rule_bases << RuleEngine::RDFSRuleBase
  re.rule_bases << RuleEngine::OWLRuleBase
  re.rule_bases << MyRuleBase
  while p re.process_rules; end
  
  namespaces = ontospec.namespaces
  namespaces.values.each { |ns| adapter.fetch ns }
end